package com.jerry.netty.buffer;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * 使用方法：
 *     1. main函数使用run方法进行启动
 *     2. 在命令提示符下使用 telnet 127.0.0.1 7000 连接服务器
 *     3. 输入ctrl + ] 进入发送模式
 *     4. 发送数据 send 12345678
 */
public class MutliBufferTest {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

        //绑定端口到socket, 并启动socket
        serverSocketChannel.socket().bind(inetSocketAddress);

        //创建buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        //等待客户端连接(可以使用telnet连接)
        SocketChannel socketChannel = serverSocketChannel.accept();

        int messageLength = 8;    //假设从客户端接收到8个字节
        //循环读取
        while (true) {
            int byteRead = 0;
            while (byteRead < messageLength) {
                long readLength = socketChannel.read(byteBuffers);
                byteRead += readLength;
                System.out.println("byteRead="+byteRead);

                //使用流打印，查看当前buffer的position和limit
                Arrays.asList(byteBuffers)
                        .stream()
                        .map(buffer -> "position="+buffer.position() + ",  limit="+buffer.limit())
                        .forEach(System.out::println);
            }

            //将所有的buffer进行flip
            Arrays.asList(byteBuffers).forEach(buffer -> buffer.flip());

            //将数据读出显示到客户端
            long byteWrite = 0;
            while (byteWrite < messageLength) {
                long writeLength = socketChannel.write(byteBuffers);
                byteWrite += writeLength;
            }

            //将所有的buffer进行clear
            Arrays.asList(byteBuffers).forEach(buffer -> buffer.clear());

            System.out.println("byteRead="+byteRead+",   byteWrite="+byteWrite+",   messageLength"+messageLength);
        }

    }
}
